/***
 Metronic AngularJS App Main Script
 ***/

/* Metronic App */
var MetronicApp = angular.module("MetronicApp", [
    "ui.router",
    "ui.bootstrap",
    "oc.lazyLoad",
    "ngSanitize",
    "ngResource",
    "ngMessages",
    "toastr",
    "ngJsTree",
    "flow",
    "ui.validate",
    "leading.datePicker",
    "leading.editor",
    "leading.select2"
]);
/* Configure ocLazyLoader(refer: https://github.com/ocombe/ocLazyLoad) */
MetronicApp.config(['$ocLazyLoadProvider', function ($ocLazyLoadProvider) {
    $ocLazyLoadProvider.config({
        // global configs go here
    });
}]);

//AngularJS v1.3.x workaround for old style controller declarition in HTML
MetronicApp.config(['$controllerProvider', function ($controllerProvider) {
    $controllerProvider.allowGlobals();
}]);

/* Setup global settings */
MetronicApp.factory('settings', ['$rootScope', function ($rootScope) {
    // supported languages
    var settings = {
        layout: {
            pageSidebarClosed: false, // sidebar menu state
            pageContentWhite: true, // set page content layout
            pageBodySolid: false, // solid body color state
            pageAutoScrollOnLoad: 1000 // auto scroll to top on page load
        },
        assetsPath: './assets',
        globalPath: './assets/global',
        layoutPath: './assets/layouts/layout'
    };

    var treeConfig = {
        core: {
            multiple: true,
            animation: true,
            error: function (error) {
                console.log('treeCtrl: error from js tree - ' + angular.toJson(error));
            },
            check_callback: true,
            worker: true
        },
        checkbox: {
            "keep_selected_style": false
        },
        version: 1,
        plugins: ['types', 'checkbox']
    };

    $rootScope.settings = settings;
    $rootScope.treeConfig = treeConfig;
    return settings;
}]);

/* Setup App Main Controller */
MetronicApp.controller('AppController', ['$scope', 'FileStorageService', function ($scope, FileStorageService) {
    $scope.$on('$viewContentLoaded', function () {

    });

    $scope.getImageSrc = function (fileNo) {
        return FileStorageService.getFileDownloadUrl(fileNo);
    };
}]);

/* Setup Layout Part - Header */
MetronicApp.controller('HeaderController', ['$scope', '$rootScope', 'AppCommonService', 'toastr','$window', function ($scope, $rootScope, AppCommonService, toastr,$window) {
    $scope.$on('$includeContentLoaded', function () {
        Layout.initHeader(); // init header
    });
    $scope.username = $.cookie("nickname") || "未知用户";
    $scope.initMenus = function () {
        AppCommonService.getMyAuthorizedMenus().$promise.then(function (result) {
            if (result.status == 'success') {
                if(typeof (result.data) === "string"){
                    result.data = JSON.parse(result.data);
                }
                if (result.data.length == 0) {
                    toastr.error('', '您目前没有权限，如需访问系统，请联系管理员分配权限');
                    console.error('您目前没有权限，如需访问系统，请联系管理员分配权限');
                }
                $rootScope.menus = result.data;
                if ($rootScope.menus && $rootScope.menus.length) {
                    var adminSidebarMenus = _.find($rootScope.menus, {"key": "admin"});
                    if (adminSidebarMenus) {
                        $rootScope.systemTitle = adminSidebarMenus.title;
                    }
                }
                if (!$scope.$$phase) {
                    $scope.$apply();
                }
                $rootScope.$broadcast("initMenuSuccess");
            } else {
                toastr.error('', '您目前没有权限，如需访问系统，请联系管理员分配权限');
                console.error('您目前没有权限，如需访问系统，请联系管理员分配权限');
            }
        });
    };

    $rootScope.$on("initMenuEvent", function () {
        $scope.initMenus();
    });
    $rootScope.$broadcast("initMenuEvent");

    $scope.switchSubsystem = function (key) {
        $rootScope.$broadcast("initMenuSuccess", {"type": "switch", "subSystem": key});
    };

    $scope.logout = function () {
        AppCommonService.logout().$promise.then(function (result) {
            if (result.status == "success") {
                var expireDate = new Date();
                expireDate.setDate(expireDate.getDate() - 1);
                $.cookie("nickname", "", {'path': "/", 'expires': expireDate});
            } else {
                for (var index in result.errors) {
                    toastr.error( result.errors[index].errmsg,"登出请求失败");
                    return;
                }
            }
        });
        $window.location.href = "./login.html";
    }
}]);

/* Setup Layout Part - Sidebar */
MetronicApp.controller('SidebarController', ['$scope', '$rootScope', function ($scope, $rootScope) {
    $scope.$on('$includeContentLoaded', function () {
        Layout.initSidebar(); // init sidebar
    });

    $scope.hasSubMenus = function (subMenus) {
        if (subMenus && subMenus.length) {
            return true;
        }
        return false;
    };

    $rootScope.$on("initMenuSuccess", function () {
        if (!$rootScope.menus || $rootScope.menus.length === 0) {
            Layout.setSidebarMenuActiveLink('match');
            return;
        }
        var adminSidebarMenus = _.find($rootScope.menus, {"key": "admin"});
        if (adminSidebarMenus && adminSidebarMenus.subMenus && adminSidebarMenus.subMenus.length) {
            $scope.sidebarMenus = adminSidebarMenus.subMenus;
        } else {
            $scope.sidebarMenus = [];
        }
    });
}]);

/* Setup Layout Part - Footer */
MetronicApp.controller('FooterController', ['$scope', function ($scope) {
    $scope.$on('$includeContentLoaded', function () {
        Layout.initFooter(); // init footer
    });
}]);

/* Init global settings and run the app */
MetronicApp.run(["$rootScope", "settings", "$state", function ($rootScope, settings, $state) {
    $rootScope.$state = $state; // state to be accessed from view
    $rootScope.$settings = settings; // state to be accessed from view
}]);
